package com.itheima.reggie.Interceptor;

import com.alibaba.fastjson.JSON;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if(empId!=null){
            //有，放行
            BaseContext.setCurrentId(empId);
            return true;
        }

        //获取登录用户
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId!=null){
            //有，放行
            BaseContext.setCurrentId(userId);
            return true;
        }
        //没有--不放行且响应给用户跳转到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
